<template>
  <div class="goods">
    <!-- 1、搜索区域 -->
    <div class="header">
      <!-- change 仅在输入框失去焦点或用户按下回车时触发 (value: string | number) -->
      <el-input v-model="keyword" placeholder="请输入内容" @change="toSearch"></el-input>
      <el-button type="primary">搜索</el-button>
      <el-button type="primary" @click="exportTable">导出表格</el-button>
      <!-- <el-button type="primary" @click="addDialog">添加</el-button> -->
    </div>
    <!-- 2、表格区域展示视图数据 -->
    <div class="wrapper">
      <el-table :data="tableData" border ref="multipleTable" :row-key="getRowKey"
        @selection-change="handleSelectionChange" stripe style="width: 100%">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="devic" label="装置" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="device_number" label="设备号" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="device_item" label="设备位号" show-overflow-tooltip width="150px"></el-table-column>

        <!-- <el-table-column prop="asset_number" label="资产号" show-overflow-tooltip width="150px"></el-table-column> -->
        <el-table-column prop="equipment_name" label="设备名称" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="specification_and_model" label="规格型号" show-overflow-tooltip
          width="150px"></el-table-column>
        <el-table-column prop="equipment_classification" label="设备分类" show-overflow-tooltip
          width="150px"></el-table-column>
        <el-table-column prop="shaft_power" label="轴功率(KW)" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="manufacturer" label="制造厂" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="rated_flow_rate" label="额定流量" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="diagram" label="简图（嵌入）" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <el-button @click="toggleSelection(tableData)">全选</el-button>
      <el-button @click="toggleSelection()">反选</el-button>
    </div>
    <!-- 3、分页 -->
    <MyPagination :total="total" :pageSize="pageSize" :currentPage="currentPage" @changePageNum="getPageNum" />
    <!-- 添加弹窗 -->
    <GoodsDialog ref="dialog" :title="title" :rowData="rowData" @changePage="getPage(1)" />
  </div>
</template>
<script>
import MyPagination from '@/components/MyPagination.vue'
import GoodsDialog from './GoodsDialog.vue'
import { export2Excel } from '@/common/js/util'
import { getGoodsList, getSearchList, delGoods } from '@/api/index.js'
export default {
  components: {
    MyPagination,
    GoodsDialog
  },
  data() {
    return {
      multipleSelection: [], //被勾选的数据
      keyword: "",
      tableData: [],
      total: 10,
      pageSize: 1,  // 一般默认值设为1
      currentPage: 1,  //当前页，让哪一页高亮
      searchList: [],  // 搜索列表
      type: 1,  //1：查询所有商品列表的分页   2：查询搜索列表的分页
      title: '设备添加',   //弹窗标题
      rowData: {},  // 整行数据
      columns: [
        { title: '设备号', key: 'devic' },
        { title: '资产号', key: 'device_number' },
        { title: '设备位号', key: 'asset_number' },
        { title: '设备名称', key: 'device_item' },
        { title: '规格型号', key: 'equipment_name' },
        { title: '设备分类', key: 'specification_and_model' },
        { title: '结构形式', key: 'equipment_classification' },
        { title: '工艺介质', key: 'structural_style' },
        { title: '密度kg/m3', key: 'process_medium' },
        { title: '正常操作温度(℃)', key: 'density_kg/m3' },
        { title: '最高操作温度(℃)', key: 'normal_operating_temperature' },
        { title: '进口操作压力(MPa)', key: 'maximum_operating_temperature' },
        { title: '出口操作压力(MPa)', key: 'import_operating_pressure' },
        { title: '最小连续流量', key: 'export_operating_pressure' },
        { title: '正常流量', key: 'minimum_continuous_flow_rate' },
        { title: '额定流量', key: 'normal_traffic' },
        { title: '扬程(mH2O)', key: 'rated_flow_rate' },
        { title: '转速r/min', key: 'head' },
        { title: '跳闸转速r/min', key: 'speed' },
        { title: '级数（容积式泵填写缸数）', key: 'trip_speed' },
        { title: '单双吸', key: 'number_of_stages' },
        { title: '流道数', key: 'single_and_double_suction' },
        { title: '必需汽蚀余量NPSHrm', key: 'number_of_flow_channels' },
        { title: '有效汽蚀余量NPSHam', key: 'required_npshrm_cavitation_allowance' },
        { title: '润滑油品', key: 'effective_cavitation_allowance' },
        { title: '润滑方式', key: 'lubricating_oil_products' },
        { title: 'API610材料代号', key: 'lubrication_method' },
        { title: '壳体材质', key: 'api610_material_code' },
        { title: '轴材质（容积式泵填写曲轴材质）', key: 'shell_material' },
        { title: '叶轮材质（容积式泵填写“柱塞杆/柱塞”材质）', key: 'shaft_material' },
        { title: '重量    (kg)', key: 'impeller_material' },
        { title: '单价    (元)', key: 'weight' },
        { title: '轴功率(KW)', key: 'unit_price' },
        { title: '效率(%)', key: 'shaft_power' },
        { title: '制造厂', key: 'efficiency' },
        { title: '出厂编号', key: 'manufacturer' },
        { title: '出厂日期', key: 'factory_number' },
        { title: '投用日期', key: 'date_of_production' },
        { title: '密封型式', key: 'date_of_use' },
        { title: '冲洗方案', key: 'sealing_type' },
        { title: '密封型号', key: 'rinse_plan' },
        { title: '装机数量', key: 'sealing_model' },
        { title: '止推轴承型号', key: 'installation_quantity' },
        { title: '止推轴承装机数量', key: 'model_of_thrust_bearing' },
        { title: '径向轴承型号', key: 'number_of_installed_thrust_bearings' },
        { title: '径向轴承装机数量', key: 'radial_bearing_model' },
        { title: '状态监测配置', key: 'number_of_radial_bearings_installed' },
        { title: '状态监测厂家', key: 'status_monitoring_configuration' },
        { title: '联轴器型式', key: 'status_monitoring_manufacturer' },
        { title: '驱动形式', key: 'coupling_type' },
        { title: '变速型式', key: 'drive_form' },
        { title: '（电机）型号', key: 'variable_speed_type' },
        { title: '（电机）功率     (KW)', key: 'motor_model' },
        { title: '（电机）额定转速     (rpm)', key: 'motor_power' },
        { title: '（电机）额定电压     (V)', key: 'motor_rated_speed' },
        { title: '（电机）额定电流      (A)', key: 'motor_rated_voltage' },
        { title: '（电机）制造厂', key: 'motor_rated_current' },
        { title: '设备分级', key: 'motor_manufacturer' },
        { title: '简图（嵌入）', key: 'equipment_classification' },
        { title: '备注', key: 'diagram' }

      ],
    }
  },
  // 生命周期函数
  created() {
    this.getGoodsList(1) //调用
  },
  methods: {
    //切换分页后，还保持全选状态
    getRowKey(row) {
      return row.id;
    },
    // 根据页码查询商品列表
    async getGoodsList(pageNum) {
      try {
        const res = await getGoodsList({ page: pageNum })
        console.log(res);
        this.tableData = res.data;
        this.total = res.total;
        this.pageSize = res.pageSize;
      } catch (error) {
        // console.log(error)
      }
    },
    // 搜索商品
    async toSearch(val) {
      console.log(val);
      //不输入值，搜索
      if (!val) {
        //加载列表的第一页数据
        this.getGoodsList(1);
        this.type = 1;  // 按列表分页
        return;
      }
      try {
        const res = await getSearchList({ search: val });
        // this.tableData = res.result;  //可能上千条数据，一次性请求增加服务器压力和前端渲染效率
        // 有1000条数据，实现分页：[]的方法
        // {status: 500, msg: '暂无数据'}
        if (res.status == 200 && res.result.length != 0) {
          // 前端模拟分页 ==> 数组分割
          this.searchList = res.result;
          this.tableData = this.searchList.slice(0, 3);
          this.total = res.result.length;  //总条数
          this.pageSize = 3;  //假设每页3条数据
          this.type = 2;  // 按搜索分页
          this.currentPage = 1;
        } else {
          // 无数据处理
          this.tableData = [];
          this.total = 0;  //总条数
          this.pageSize = 1;
          this.type = 1;  //所有数据分页
        }
      } catch (error) {
        // 无数据处理（这里是说有可能在发送过程中，断网了，接收不到数据的处理）
        this.tableData = [];
        this.total = 0;  //总条数
        this.pageSize = 1;
        this.type = 1;  //所有数据分页
        console.log(error);
      }
    },
    // 父组件接收 分页子组件传过来的页码
    getPageNum(page) {
      this.currentPage = page;  //点击页码，让当前页码高亮
      console.log(page);
      if (this.type == 1) {
        this.getGoodsList(page);  // 查询所有商品分页
      } else {
        // 搜索分页 ，切割数据  0,1,2  3,4,5  6,7,8   slice(,)  0,3  3,6  6,9
        // ((page-1)*3,page*3)
        this.tableData = this.searchList.slice((page - 1) * 3, page * 3);  //搜索完记得让type标记变为为2
      }
    },
    // 跳转到新页面去添加
    toAdd() {
      this.$router.push('/add-goods');
      this.title = "设备添加";
    },
    // 弹窗 添加商品页面
    addDialog() {
      this.$refs.dialog.dialogVisible = true;
      this.title = "设备添加";
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.$refs.dialog.dialogVisible = true; //显示弹窗
      this.title = "设备编辑";
    },
    // 给子组件传值
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('你确定要删除设备吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {  // eslint-disable-line no-unused-vars
        // 删除商品，请求后台
        try {
          const res = await delGoods({ id: row.id })
          console.log(res);
          if (res.status == 200) {
            this.getGoodsList(1);  //更新列表，并展示第一页数据
            this.currentPage = 1;  //让页码在在第一页高亮
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
          }
        } catch (error) {
          console.log(error);
        }
      }).catch(() => {
        console.log('取消删除');
        this.$message({
          message: '已取消删除！',
          type: 'info'
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //全选和反选（对当前页数据）
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleAllSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //为了让商品在添加或编辑后，刷新数据，并展示第一页数据时，让页码在在第一页高亮
    getPage(page) {
      this.currentPage = page;
    },
    exportTable() {
      // export2Excel('表头', '需要导出的数据')
      export2Excel(this.columns, this.tableData, '设备清册')
    }
  }
}
</script>
<style lang="less" scoped>
.goods {
  padding: 20px;

  .header {
    display: flex; //弹性布局

    button {
      margin-left: 20px;
    }
  }

  .wrapper {
    padding: 20px 0;
    overflow-x: auto;
    /* 添加横向滚动条 */
  }
}
</style>
